package com.cykj.pos.controller.api;

import java.util.*;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.cykj.pos.controller.TestDTO.HttpClientHandler;
import com.cykj.pos.domain.BizFeesCharged;
import com.cykj.pos.domain.BizPosMachine;
import com.cykj.pos.service.IBizFeesChargedService;
import com.cykj.pos.service.IBizPosMachineService;
import com.cykj.pos.util.PosOneUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.cykj.common.annotation.Log;
import com.cykj.common.core.controller.BaseController;
import com.cykj.common.core.domain.AjaxResult;
import com.cykj.common.enums.BusinessType;
import com.cykj.pos.domain.BizTrackRecord;
import com.cykj.pos.service.IBizTrackRecordService;
import com.cykj.common.utils.poi.ExcelUtil;
import com.cykj.common.core.page.TableDataInfo;

import javax.annotation.Resource;

/**
 * 追溯记录Controller
 *
 * @author xxl
 * @date 2022-03-28
 */
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/pos/record" )
public class BizTrackRecordController extends BaseController {

    private final IBizTrackRecordService iBizTrackRecordService;

    private final IBizFeesChargedService bizFeesChargedService;

    private final IBizPosMachineService bizPosMachineService;

    /**
     * 查询追溯记录列表
     */
    @PreAuthorize("@ss.hasPermi('pos:record:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizTrackRecord bizTrackRecord) {
        startPage();
        List<BizTrackRecord> list = iBizTrackRecordService.queryList(bizTrackRecord);
        return getDataTable(list);
    }

    /**
     * 导出追溯记录列表
     */
    @PreAuthorize("@ss.hasPermi('pos:record:export')" )
    @Log(title = "追溯记录" , businessType = BusinessType.EXPORT)
    @GetMapping("/export" )
    public AjaxResult export(BizTrackRecord bizTrackRecord) {
        List<BizTrackRecord> list = iBizTrackRecordService.queryList(bizTrackRecord);
        ExcelUtil<BizTrackRecord> util = new ExcelUtil<BizTrackRecord>(BizTrackRecord.class);
        return util.exportExcel(list, "record" );
    }

    /**
     * 获取追溯记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('pos:record:query')" )
    @GetMapping(value = "/{id}" )
    public AjaxResult getInfo(@PathVariable("id" ) Long id) {
        return AjaxResult.success(iBizTrackRecordService.getById(id));
    }

    /**
     * 新增追溯记录
     */
    @PreAuthorize("@ss.hasPermi('pos:record:add')" )
    @Log(title = "追溯记录" , businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizTrackRecord bizTrackRecord) {
        return toAjax(iBizTrackRecordService.save(bizTrackRecord) ? 1 : 0);
    }

    /**
     * 修改追溯记录
     */
    @PreAuthorize("@ss.hasPermi('pos:record:edit')" )
    @Log(title = "追溯记录" , businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizTrackRecord bizTrackRecord) {
        return toAjax(iBizTrackRecordService.updateById(bizTrackRecord) ? 1 : 0);
    }

    /**
     * 删除追溯记录
     */
    @PreAuthorize("@ss.hasPermi('pos:record:remove')" )
    @Log(title = "追溯记录" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}" )
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(iBizTrackRecordService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }


    @PostMapping("/timerGet")
    public  void  timerGet(@RequestBody BizPosMachine bizPosMachine) throws Exception {
        //查询所有的设备
        System.out.println("------------------------------");
        System.out.println("-----------报件 绑定 查询费用收取列表-------------------"+new Date());
        System.out.println("------------------------------");
        //  List<BizPosMachine> bizPosMachineList = bizPosMachineService.timerGetAllPos();
        //   for (BizPosMachine bizPosMachine : bizPosMachineList) {
        //循环查询费用收取列表
        //  String snCode = bizPosMachine.getPosCode();
        String snCode = bizPosMachine.getPosCode();
        Map<String, String> data2 = new HashMap<String, String>();
        String url2 = "http://wx.wenwenpay.com.cn:6080/vipf/merchantinfo.do?action=handleAction&beanName=teramtDao&Methods=list";
        data2.put("sn", snCode);
        data2.put("mersource", "OUTMER");
        data2.put("agentid", "NP2T1215");
        data2.put("key", "c2cad9ae77f74e618ae672b122ee6496");
        data2.put("sign", PosOneUtil.generateSignature(data2));
        System.out.println("----------" + PosOneUtil.generateSignature(data2));
        System.out.println("---------" + data2);
        String result2 = HttpClientHandler.noPictureRequest(url2, data2);
        System.out.println("返回:" + result2);
        JSONObject jsonObject2 = JSONObject.parseObject(result2);
        String retCode2 = jsonObject2.getString("ret_code");
        JSONObject data4 = jsonObject2.getJSONObject("data");
        Integer totcount = data4.getInteger("totcount");
        JSONArray list = data4.getJSONArray("list");
        if (retCode2.equals("0") ) { //判断是否获取成功
            if (totcount > 0) { //判断是否查询到条数
                if (list.size() > 0) {  // 判断查寻到的list是否有值
                    for (int i = 0; i < list.size(); i++) {
                        JSONObject jsonObject1 = list.getJSONObject(i);
                        String mamount_id = jsonObject1.getString("mamount_id"); //费用ID(隐藏)
                        String orgnname = jsonObject1.getString("orgnname");   //所属代理
                        String merchant_no = jsonObject1.getString("merchant_no");  //系统商户编号
                        String sn = jsonObject1.getString("sn");  //SN
                        String simcardfee = jsonObject1.getString("simcardfee");  //收取费用
                        String mamount_starts = jsonObject1.getString("mamount_starts");  //状态(0-初始 1-成功 2-取消 3-待收取 9-未知)
                        String amt_type = jsonObject1.getString("amt_type");  //费用类型（0-流量费 1-设备款）
                        String creatdate = jsonObject1.getString("creatdate");  //创建日期
                        //查询成功 查询的信息存到 费用收取列表
                        if (!mamount_starts.equals("1") && !mamount_starts.equals("2") && amt_type.equals("0")) {
                            BizFeesCharged bizFeesCharged = new BizFeesCharged();
                            bizFeesCharged.setMamountId(mamount_id);
                            bizFeesCharged.setOrgnname(orgnname);
                            bizFeesCharged.setMerchantNo(merchant_no);
                            bizFeesCharged.setSn(sn);
                            bizFeesCharged.setSimcardfee(simcardfee);
                            bizFeesCharged.setMamountStarts(mamount_starts);
                            bizFeesCharged.setAmtType(amt_type);
                            bizFeesCharged.setCreatdate(creatdate);
                            bizFeesCharged.setUuid(IdWorker.getIdStr());
                            BizFeesCharged byId = bizFeesChargedService.getById(mamount_id);
                            if (byId == null){
                                bizFeesChargedService.insertBizFeesCharged(bizFeesCharged);
                            }
                        }
                    }
                } else {
                    System.out.println("没有list");
                }
            }
        }
        // }
    }
}
